import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import FormInput from '../components/FormInput';
import SubmitButton from '../components/SubmitButton';
import { resetPassword } from '../services/api';

// 从URL中获取token
const token = localStorage.token || ''

const ResetPassword: React.FC = () => {
    const navigate = useNavigate();
    const [newPassword, setNewPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [error, setError] = useState('');

    const handleReset = async () => {
        if (newPassword !== confirmPassword) {
            setError('两次新密码不一致');
            return;
        }
        try {
            await resetPassword(token, newPassword, confirmPassword);
            navigate('/login');
        } catch (err: any) {
            setError(err.response?.data?.error || '重置密码失败');
        }
    };

    return (
        <div className="auth-container">
            <h2>重置密码</h2>
            <p>请设置您的新密码</p>
            {error && <p className="error">{error}</p>}
            <FormInput label="新密码" placeholder="请输入新密码" type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />
            <FormInput label="确认新密码" placeholder="请确认新密码" type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} />
            <SubmitButton text="重置密码" onClick={handleReset} />
            <p><a href="#" onClick={() => navigate('/login')}>返回登录</a></p>
        </div>
    );
};

export default ResetPassword;
